import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { userService } from '../../services/user';
import UserLayout from './UserLayout';
import './Profile.css';

const Profile = () => {
  const navigate = useNavigate();
  const [userData, setUserData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [editMode, setEditMode] = useState(false);
  const [formData, setFormData] = useState({
    username: '',
    avatar: null,
  });

  useEffect(() => {
    fetchUserProfile();
  }, []);

  const fetchUserProfile = async () => {
    try {
      const response = await userService.getProfile();
      // 兼容304响应和本地缓存
      if (response.status === 200 && response.data.code === 200) {
        setUserData(response.data.data);
        setFormData({
          username: response.data.data.username,
          avatar: null,
        });
        // 同步本地缓存
        localStorage.setItem('user', JSON.stringify(response.data.data));
      } else if (response.status === 304) {
        // 304时尝试用本地缓存
        const cached = localStorage.getItem('user');
        if (cached) {
          const data = JSON.parse(cached);
          setUserData(data);
          setFormData({
            username: data.username,
            avatar: null,
          });
        } else {
          setError('获取用户信息失败（无缓存）');
        }
      } else {
        setError('获取用户信息失败');
      }
    } catch (err) {
      // 也尝试用本地缓存兜底
      const cached = localStorage.getItem('user');
      if (cached) {
        const data = JSON.parse(cached);
        setUserData(data);
        setFormData({
          username: data.username,
          avatar: null,
        });
      } else {
        setError('获取用户信息失败');
      }
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e) => {
    const { name, value, files } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: files ? files[0] : value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      const formDataToSend = new FormData();
      formDataToSend.append('username', formData.username);
      if (formData.avatar) {
        formDataToSend.append('avatar', formData.avatar);
      }

      const response = await userService.updateProfile(formDataToSend);
      if (response.data.code === 200) {
        setUserData(response.data.data);
        setEditMode(false);
        // 更新本地存储的用户信息
        localStorage.setItem('user', JSON.stringify(response.data.data));
      }
    } catch (err) {
      setError(err.response?.data?.message || '更新失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <UserLayout>
        <div className="content-loading">加载中...</div>
      </UserLayout>
    );
  }

  if (!userData) {
    return (
      <UserLayout>
        <div className="content-error">{error || '获取用户信息失败'}</div>
      </UserLayout>
    );
  }

  return (
    <UserLayout>
      <div className="profile-content">
        <div className="profile-header">
          <h2 className="content-title">个人资料</h2>
          <div className="avatar-container-corner">
            <img src={userData.avatarUrl} alt="用户头像" className="user-avatar1" />
          </div>
        </div>
        
        {error && <div className="error-message">{error}</div>}
        
        {editMode ? (
          <div className="profile-form-container">
            <form onSubmit={handleSubmit} className="profile-form">
              <div className="form-group">
                <label htmlFor="username">用户名</label>
                <input
                  type="text"
                  id="username"
                  name="username"
                  value={formData.username}
                  onChange={handleChange}
                  required
                />
              </div>
              <div className="form-group">
                <label htmlFor="avatar">头像</label>
                <input
                  type="file"
                  id="avatar"
                  name="avatar"
                  onChange={handleChange}
                  accept="image/*"
                />
              </div>
              <div className="form-actions">
                <button type="submit" className="primary-btn" disabled={loading}>
                  {loading ? '保存中...' : '保存'}
                </button>
                <button type="button" className="cancel-btn" onClick={() => setEditMode(false)}>
                  取消
                </button>
              </div>
            </form>
          </div>
        ) : (
          <div className="profile-info-container">
            <div className="info-content">
              <div className="info-row">
                <label>用户名</label>
                <p>{userData.username}</p>
              </div>
              <div className="info-row">
                <label>邮箱</label>
                <p>{userData.email}</p>
              </div>
              <div className="info-row">
                <label>邀请码</label>
                <p>{userData.invitationCode}</p>
              </div>
              <div className="info-row">
                <label>注册时间</label>
                <p>{new Date(userData.createdAt).toLocaleString()}</p>
              </div>
            </div>
            <div className="edit-container">
              <button onClick={() => setEditMode(true)} className="edit-btn">
                编辑资料
              </button>
            </div>
          </div>
        )}
      </div>
    </UserLayout>
  );
};

export default Profile; 